// pages/payForm/payForm.js
const app = getApp()
var request = require("../../utils/request.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    time: 2 * 60 * 1000,
    timeData: {},
    popShow: false,
    orderInfo: {},
    payTypeList: [],
    monthCardCheck: false,
    chargeTimeCheck: false,
    nonuse: false,
    durationTime: 0,
    checkText: '',
    useMonthCard: false,
    hasCarNumber: true,
    parkDuration: '',
    mustFinish: false,
    showBindPhone: false,
    couponText: '请选择',
    needPayTime: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let opendId = wx.getStorageSync('opneId');
    let userId = wx.getStorageSync('userId');
    console.log('userId is:', userId);
    that.getUserInfo(userId);
    that.setData({
      userId: userId,
      mustFinish: false
    })
    if (options.carCardNum) {
      let carCardNum = options.carCardNum;
      that.getOrderInfo(carCardNum);
      that.setData({
        carCardNum: carCardNum,
        hasCarNumber: true
      })
    } else if (options.q) {
      let qrUrl = decodeURIComponent(options.q)
      var channelId = that.getQueryString(qrUrl, 'channelid');
      var carParkId = that.getQueryString(qrUrl, 'carparkid');
      that.setData({
        channelId: channelId,
        carParkId: carParkId,
        hasCarNumber: false
      })
      if (userId != undefined && userId != '') {
        that.getOrderInfoByDao(channelId, carParkId, userId);
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    let ticketCode = that.data.ticketCode;
    if (ticketCode != '' && ticketCode != undefined) {
      that.setData({
        checkText: '停车优惠券'
      })
      that.updataOrder(ticketCode);
    }
  },
  /**
   * 倒计时
   */
  onChange(e) {
    this.setData({
      timeData: e.detail
    });
  },
  /**
   * 倒计时结束时触发，重新请求后台获取订单
   */
  onFinish() {
    let mustFinish = this.data.mustFinish;
    if (!mustFinish) {
      let that = this;
      let hasCarNumber = that.data.hasCarNumber;
      if (hasCarNumber) {
        let carCardNum = that.data.carCardNum;
        that.getOrderInfo(carCardNum);
      } else {
        let channelId = that.data.channelId;
        let carParkId = that.data.carParkId;
        let userId = that.data.userId;
        that.getOrderInfoByDao(channelId, carParkId, userId);
      }
      that.start();
    }
  },
  /**
   * 开始倒计时
   */
  start() {
    this.reset();
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },
  reset() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.reset();
  },
  /**
   * 弹窗展示
   */
  showPop() {
    this.setData({
      popShow: true
    })
  },
  /**
   * 关闭展示
   */
  popShowClose() {
    this.setData({
      popShow: false
    })
  },
  /**
   * 获取订单详情
   * @param {String} 车牌号 
   */
  getOrderInfo(carCardNum) {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let url = "/api/endCar/endCarhInByCarNum?carNo=" + carCardNum + "&uid=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let orderInfo = res.data.data;
          if (orderInfo != null && orderInfo != undefined) {
            let parkDuration = orderInfo.parkDuration
            orderInfo.parkDuration = that.getDuration(orderInfo.parkDuration);
            let chargeTimeCheck = that.data.chargeTimeCheck;
            if (chargeTimeCheck) {
              orderInfo.receivedCost = 0;
            }
            that.setData({
              orderInfo: orderInfo,
              parkDuration: parkDuration
            })
            that.getPayType(orderInfo);
          }
        } else {
          Toast(res.data.message);
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 将毫秒转化
   * @param {String} my_time 毫秒
   */
  getDuration(my_time) {
    var days = my_time / 1000 / 60 / 60 / 24;
    var daysRound = Math.floor(days);
    var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
    var hoursRound = Math.floor(hours);
    var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
    var minutesRound = Math.floor(minutes);
    var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
    if (daysRound != '' && daysRound > 0) {
      var time = daysRound + '天' + hoursRound + '小时' + minutesRound + '分钟';
    } else if (daysRound == 0 && hoursRound != '' && hoursRound > 0) {
      var time = hoursRound + '小时' + minutesRound + '分钟';
    } else if (hoursRound == 0 && minutesRound != '' && minutesRound > 0) {
      var time = minutesRound + '分钟';
    }
    return time;
  },
  /**
   * 转化时长抵扣
   * @param {String} my_time 毫秒
   */
  changePayTime(my_time) {
    var hours = my_time / 1000 / 60 / 60;
    var hoursRound = Math.floor(hours);
    var minutes = my_time / 1000 / 60 - (60 * hoursRound);
    var minutesRound = Math.floor(minutes);
    if (minutesRound > 0) {
      hoursRound += 1;
    }
    return hoursRound;
  },
  /**
   * 获取当前可用的支付方式
   * @param {String} orderInfo 订单信息
   */
  getPayType(orderInfo) {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let carNum = orderInfo.carCardNum;
    let parkDuration = that.data.parkDuration;
    let url = "/api/endCar/getPayType?carNum=" + carNum + "&uid=" + userId + "&parkDuration=" + parkDuration;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          if (res.data.data != null && res.data.data != undefined) {
            let monthCardInfo = res.data.data.bParkingleaserecord;
            let chargeTimeInfo = res.data.data.cDurationrecord;
            //如果拥有月卡
            if (monthCardInfo != null && monthCardInfo != undefined) {
              monthCardInfo.beginTime = monthCardInfo.beginTime.substring(0, 10);
              monthCardInfo.endTime = monthCardInfo.endTime.substring(0, 10);
              that.setData({
                useMonthCard: true,
                monthCardInfo: monthCardInfo
              })
            }
            if (chargeTimeInfo != null && chargeTimeInfo != undefined) {
              that.setData({
                chargeTimeInfo: chargeTimeInfo
              })
            }
          }
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 月租卡是否选中
   */
  cardCheck() {
    let that = this;
    let monthCardCheck = that.data.monthCardCheck;
    if (!monthCardCheck) {
      that.setData({
        checkText: '月租卡'
      })
    }
    that.setData({
      monthCardCheck: !monthCardCheck,
      chargeTimeCheck: false,
      nonuse: false
    })
  },
  /**
   * 判断充值时长是否选中
   */
  chargeCheck() {
    let that = this;
    let chargeTimeCheck = that.data.chargeTimeCheck;
    let parkDuration = that.data.parkDuration;
    if (!chargeTimeCheck) {
      let orderInfo = that.data.orderInfo;
      orderInfo.receivedCost = 0;
      that.setData({
        checkText: '充值时长',
        orderInfo: orderInfo
      })
    }
    that.setData({
      chargeTimeCheck: !chargeTimeCheck,
      monthCardCheck: false,
      nonuse: false
    })
  },
  /**
   * 判断不使用是否选中
   */
  noCheck() {
    let that = this;
    let nonuse = that.data.nonuse
    if (!nonuse) {
      let carCardNum = that.data.carCardNum;
      that.getOrderInfo(carCardNum);
      that.setData({
        checkText: '微信支付'
      })
    }
    that.setData({
      nonuse: !nonuse,
      monthCardCheck: false,
      chargeTimeCheck: false
    })
  },
  /**
   * 确认缴费
   */
  submit() {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let orderInfo = that.data.orderInfo;
    let body = '停车缴费';
    let orderId = orderInfo.orderId;
    let chargeTimeCheck = that.data.chargeTimeCheck;
    let totalFee = orderInfo.receivedCost;
    let type = 2;
    let hasCarNumber = that.data.hasCarNumber;
    let code = 0;
    let qureType = 0;
    if (!hasCarNumber) {
      //当前为通道码进入
      code = that.data.channelId;
      qureType = 1;
    }
    if (chargeTimeCheck) {
      totalFee = 0;
      type = 1;
    }
    let url = "/api/pay/miniPaysV2?body=" + body + "&uid=" + userId + "&totalFee=" + totalFee + "&orderId=" + orderId + '&type=' + type + "&code=" + code + "&qureType=" + qureType;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          //如果是时长抵扣
          let body = res.data.data;
          if (chargeTimeCheck) {
            wx.redirectTo({
              url: '../paySuccess/paySuccess?totalFee=' + totalFee,
            })
          } else {
            //微信支付
            if (body.toPay == 0) {
              wx.redirectTo({
                url: '../paySuccess/paySuccess?totalFee=' + totalFee,
              })
            } else {
              wx.requestPayment({
                timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
                nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
                package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
                signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
                paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
                success: function (res) { // 成功后的回调函数
                  Toast.success('支付成功');
                  wx.redirectTo({
                    url: '../paySuccess/paySuccess?totalFee=' + totalFee,
                  })
                },
                fail(res) {
                  // Toast.fail('支付失败');
                  console.log(res)
                }
              })
            }
          }
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 获取停车券列表
   */
  getCouponList() {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let orderInfo = that.data.orderInfo;
    let type = '';
    let monthCardCheck = that.data.monthCardCheck,
      chargeTimeCheck = that.data.chargeTimeCheck,
      nonuse = that.data.nonuse;
    if (monthCardCheck) {
      that.popShowClose();
      return
    } else if (chargeTimeCheck) {
      type = 0;
    } else {
      type = 1;
    }
    let parkId = orderInfo.parkId;
    let url = "/api/cMyticket/getNUseDSCTickets?type=" + type + "&userId=" + userId + "&parkId=" + parkId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let couponList = res.data.data;
          if (couponList != null && couponList.length > 0) {
            wx.navigateTo({
              url: '../checkCoupon/checkCoupon?parkId=' + parkId + '&type=' + type,
            })
          } else {
            that.setData({
              couponText: '暂无'
            })
            Toast('暂无停车优惠券');
          }
          that.popShowClose();
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 使用优惠券后更新订单
   * @param {String} ticketCode 停车券code
   */
  updataOrder(ticketCode) {
    let that = this;
    let orderId = that.data.orderInfo.orderId;
    let carCardNum = that.data.carCardNum;
    let userId = wx.getStorageSync('userId');
    let url = "/api/endCar/updateOrderByOrderId?orderId=" + orderId + "&uid=" + userId + "&ticketId=" + ticketCode;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          that.getOrderInfo(carCardNum);
        }
      }).catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  //回调支付
  // payCallBack(body) {
  //   let that = this;
  //   let url = "/api/pay/wechat/callback";
  //   var params = body;
  //     request.http(url,'POST, params).then((res) => {
  //       if (res.data.status == 200) {
  //         let totalFee = that.data.orderInfo.receivedCost;
  //         wx.redirectTo({
  //           url: '../paySuccess/paySuccess?totalFee=' + totalFee,
  //         })
  //       }
  //     })
  // },
  /**
   * 授权
   */
  bindGetUserInfo: function (e) {
    let that = this;
    let userInfo = e.detail.userInfo;
    that.setData({
      userInfo: userInfo
    })
    if (userInfo) {
      wx.login({
        success: res => {
          that.getOpenId(res.code);
        }
      });
    }
  },
  /**
   * 获取opendId
   * @param {String} code 微信返回的code
   */
  getOpenId(code) {
    let that = this;
    let info = that.data.userInfo;
    let userInfo = {
      headUrl: info.avatarUrl,
      nickName: info.nickName,
      sex: info.gender,
    }
    let url = "/api/pay/getOpenId?code=" + code;
    var params = userInfo;
    request.http(url, 'POST', params)
      .then((res) => {
        if (res.data.code == 200) {
          let openId = res.data.data.openId;
          let userId = res.data.data.userId;
          that.getUserInfo(userId);
          let session_key = res.data.data.session_key;
          wx.setStorageSync('sessionKey', session_key);
          wx.setStorageSync('openId', openId);
          wx.setStorageSync('userId', userId);
          let channelId = that.data.channelId;
          let carParkId = that.data.carParkId;
          that.getOrderInfoByDao(channelId, carParkId, userId);
          that.setData({
            openId: openId,
            userId: userId
          })
        } else {
          Toast.fail('获取失败');
        }
      }).catch((errMsg) => {
        // wx.showToast({
        //   title: '获取失败',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 通过通道码获取订单详情
   * @param {String} channelId 通道ID
   * @param {String} carParkId 车场ID
   * @param {String} userId 用户ID
   */
  getOrderInfoByDao(channelId, carParkId, userId) {
    let that = this;
    let url = "/api/endCar/ChannelCodeEndCar?channelId=" + channelId + "&uid=" + userId + "&carParkId=" + carParkId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let orderInfo = res.data.data;
          let parkDuration = orderInfo.parkDuration;
          orderInfo.parkDuration = that.getDuration(orderInfo.parkDuration);
          let carCardNum = orderInfo.carCardNum;
          that.getPayType(orderInfo);
          that.setData({
            orderInfo: orderInfo,
            carCardNum: carCardNum,
            parkDuration: parkDuration
          })
        } else {
          Toast.loading({
            mask: true,
            message: res.data.message
          });
        }
      }).catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 获取小程序二维码参数
   * @param {String} scene 需要转换的参数字符串
   */
  getQueryString: function (url, name) {
    var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
    var r = url.substr(1).match(reg)
    if (r != null) {
      return r[2]
    }
    return null;
  },
  toSuccess() {
    wx.redirectTo({
      url: '../paySuccess/paySuccess?totalFee=0',
    })
  },
  onUnload() {
    console.log('进这里了吗？');
    this.setData({
      mustFinish: true
    })
  },
  /**
   * 
   */
  showBindPhone() {
    this.setData({
      showBindPhone: true
    })
  },
  /**
   * 关闭提示绑定手机号的弹窗
   */
  closeBindPop() {
    this.setData({
      showBindPhone: false
    })
  },
  /**
   * 获取手机号
   */
  getPhoneNumber: function (e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let encryptedData = e.detail.encryptedData;
      let iv = e.detail.iv;
      that.setData({
        encryptedData: encryptedData,
        iv: iv
      })
      wx.login({
        success: res => {
          if (res.code) {
            let code = res.code;
            wx.checkSession({
              success: function (res) {
                var sessionKey = wx.getStorageSync('sessionKey');
                var userId = wx.getStorageSync('userId');
                let url = "/api/cUser/updateMobilePhone?iv=" + iv + "&encryptedData=" + encryptedData + "&userId=" + userId + "&code=" + code;
                request.http(url, 'POST')
                  .then((res) => {
                    if (res.data.code == 200) {
                      Toast.success('绑定成功');
                      let userId = wx.getStorageSync('userId');
                      that.getUserInfo(userId);
                      that.closeBindPop();
                    } else {
                      Toast.fail('绑定失败');
                    }
                  })
                  .catch((errMsg) => {
                    // wx.showToast({
                    //   title: '绑定失败',
                    //   icon: 'loading',
                    //   duration: 1000,
                    // })
                  });
              },
              fail: function (res) {
                wx.login({
                  success: res => {
                    if (res.code) {
                      that.getOpenId(res.code);
                    }
                  }
                })
              }
            })
          }
        }
      })
    }
  },
  /**
   * 获取用户信息
   */
  getUserInfo(userId) {
    let that = this;
    let url = "/api/cUser/myInfo?userId=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data.user;
          let mobilePhone = user.mobilePhone;
          if (mobilePhone == null || mobilePhone == undefined || mobilePhone == '') {
            that.setData({
              showBindPhone: true
            })
          } else {
            that.setData({
              showBindPhone: false
            })
          }
        } else {
          Toast.fail('网络错误');
        }
      })
  },
})